﻿using RndMaterialDisposalService.Cache;
using RndMaterialDisposalService.Helper;
using RndMaterialDisposalService.Models.Entitys;
using RndMaterialDisposalService.Models.RequestModel;
using RndMaterialDisposalService.Services;
using RndMaterialDisposalService.Services.Interface;
using AutoMapper;
using Masuit.Tools;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json.Linq;
using NPOI.OpenXmlFormats.Spreadsheet;
using NPOI.POIFS.Crypt.Dsig;
using NPOI.SS.Formula.PTG;
using System.Text.Json;

namespace RndMaterialDisposalService.Controllers
{
    /// <summary>
    /// 
    /// </summary>
    [Route("api/[controller]")]
    [ApiController]
    public class SyncWeinxinUserController : ControllerBase
    {
        private readonly ILogger<SyncWeinxinUserController> logger;
        private readonly IWeinxinUserService weixinService;
        private readonly ICacheContext cacheContext;
        private readonly ITokenService tokenService;
        private readonly IMapper mapper;


        /// <summary>
        /// 
        /// </summary>
        /// <param name="_logger"></param>
        /// <param name="_weixinService"></param>
        /// <param name="_cacheContext"></param>
        /// <param name="_tokenService"></param>
        /// <param name="_mapper"></param>
        public SyncWeinxinUserController(
            ILogger<SyncWeinxinUserController> _logger,
            IWeinxinUserService _weixinService,
            ICacheContext _cacheContext,
            ITokenService _tokenService,
            IMapper _mapper)
        {
            weixinService = _weixinService;
            cacheContext = _cacheContext;
            tokenService = _tokenService;
            mapper = _mapper;
            logger = _logger;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        [HttpGet("CreateUser")]
        public async Task<IActionResult> CreateUser()
        {
            var weixinToken = await tokenService.GetWeixinToken();
            var url = $"https://qyapi.weixin.qq.com/cgi-bin/user/create?access_token={weixinToken}";
            var userlist = await weixinService.GetAddUserList();

            await userlist.ForeachAsync(async (user) =>
            {
                 try
                 {
                     user.Status = 2;
                     user.ErrorMsg = "";

                     var data = mapper.Map<WeixinUserReq>(user);
                     data.Department = new List<int>() { 1 };
                     var result = await HttpHelper.PostAsync(url, JsonSerializer.Serialize(data));

                     logger.LogDebug(result);

                     var jsonObj = JObject.Parse(result);
                     if (jsonObj.Value<string>("errcode") != "0")
                     {
                         user.ErrorMsg = jsonObj.Value<string>("errmsg");
                         user.Status = 3;
                     }
                 }
                 catch (Exception ex)
                 {
                     user.ErrorMsg = ex.Message;
                     user.Status = 3;
                 }
             });

            await weixinService.UpdateSyncStatus(userlist);

            await weixinService.AddUserSyncLog(userlist, "create");

            var success = userlist.Where(p => p.Status == 2).ToList().Count;
            var failed = userlist.Where(p => p.Status == 3).ToList().Count;

            return Ok(new { action = "add", success, failed });
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        [HttpGet("UpdateUserInfo")]
        public async Task<IActionResult> UpdateUserInfo()
        {
            var weixinToken = await tokenService.GetWeixinToken();
            var url = $"https://qyapi.weixin.qq.com/cgi-bin/user/update?access_token={weixinToken}";
            var userlist = await weixinService.GetModifyUserList();

            await userlist.ForeachAsync(async (user) =>
            {
                try
                {
                    user.Status = 2;
                    user.ErrorMsg = "";

                    var data = mapper.Map<WeixinUserReq>(user);
                    data.Department = new List<int>() { 1 };
                    var result = await HttpHelper.PostAsync(url, JsonSerializer.Serialize(data));

                    logger.LogDebug(result);

                    var jsonObj = JObject.Parse(result);
                    if (jsonObj.Value<string>("errcode") != "0")
                    {
                        user.ErrorMsg = jsonObj.Value<string>("errmsg");
                        user.Status = 3;
                    }
                }
                catch (Exception ex)
                {
                    user.ErrorMsg = ex.Message;
                    user.Status = 3;
                }
            });
            
            await weixinService.UpdateSyncStatus(userlist);

            await weixinService.AddUserSyncLog(userlist, "update");

            var success = userlist.Where(p => p.Status == 2).ToList().Count;
            var failed = userlist.Where(p => p.Status == 3).ToList().Count;

            return Ok(new { action = "update", success, failed });
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        [HttpGet("BatchDeleteUser")]
        public async Task<IActionResult> BatchDeleteUser()
        {
            var errorMsg = "";
            var status = 2;
            var weixinToken = await tokenService.GetWeixinToken();
            var url = $"https://qyapi.weixin.qq.com/cgi-bin/user/batchdelete?access_token={weixinToken}";
            var userlist = await weixinService.GetDeleteUserIdList();
            try
            {
                var userId = userlist.Select(p => p.EmployeeId).ToList();
                var result = await HttpHelper.PostAsync(url, JsonSerializer.Serialize(new { useridlist = userId }));
                logger.LogDebug(result);
                var jsonObj = JObject.Parse(result);
                var errorcode = jsonObj.Value<string>("errcode");
                if (errorcode != "0") {
                    status = 3;
                    errorMsg = jsonObj.Value<string>("errmsg");
                }
            }
            catch (Exception ex)
            {
                errorMsg = ex.Message;
                status = 3;
            }
            
            userlist.ForEach(item => { item.ErrorMsg = errorMsg; item.Status = status; });
            await weixinService.UpdateSyncStatus(userlist);

            await weixinService.AddUserSyncLog(userlist, "batchdelete");

            await weixinService.DeleteMiddleTableUser(userlist.Where(p => p.Status == 2).ToList());

            var success = userlist.Where(p => p.Status == 2).ToList().Count;
            var failed = userlist.Where(p => p.Status == 3).ToList().Count;

            return Ok(new { action="delete", success, failed });
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        [HttpGet("SynchUserToMiddleTable")]
        public async Task<IActionResult> SynchUserToMiddleTable()
        {
            var result = await weixinService.SyncUserToMiddleTable();
            return Ok(result);
        }

        
    }
}
